package com.liuqi.aiagent.util;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author liuqi
 * @date 2025/7/15
 **/
public final class NetUtil {

    private static final String URL_REGEX =
            "^https?://" +
                    "(" +
                    "(?:[0-9]{1,3}\\.){3}[0-9]{1,3}" +
                    "|" +
                    "(?:[a-zA-Z0-9-]+\\.)+[a-zA-Z]{2,}" +
                    ")" +
                    "(:[0-9]{1,5})?" +
                    "(/[a-zA-Z0-9-._~:/?#\\[\\]@!$&'()*+,;=%]*)*" +
                    "(\\?[a-zA-Z0-9-._~:/?#\\[\\]@!$&'()*+,;=%]*)?" +
                    "(#[a-zA-Z0-9-._~:/?#\\[\\]@!$&'()*+,;=%]*)?$";
    private static final Pattern PATTERN_URL_REGEX = Pattern.compile(URL_REGEX);

    private static final String URL_PARSE = "^([hH][tT][tT][pP][sS]?)://([^/\\:\\s]+)(?::(\\d+))?";
    private static final Pattern PATTERN_URL_PARSE = Pattern.compile(URL_PARSE);

    /**
     * 有效的 http URL路径
     *
     * @param url
     * @return
     */
    public static boolean isHttpURL(String url) {
        if (url == null || url.isEmpty()) {
            return false;
        }
        Matcher matcher = PATTERN_URL_REGEX.matcher(url);
        return matcher.matches();
    }

    /**
     * 测试http url是否可以连接
     *
     * @param url
     * @return
     * @throws IOException
     */
    public static boolean telnetHttpURL(String url) throws IOException {
        return telnetHttpURL(url, 10000);
    }

    public static boolean telnetHttpURL(String url, int timeout) throws IOException {
        if (!isHttpURL(url)) {
            return false;
        }
        Matcher matcher = PATTERN_URL_PARSE.matcher(url);
        if (matcher.find()) {
            String protocol = matcher.group(1);   // 协议
            String host = matcher.group(2);       // 域名或IP
            String port = matcher.group(3);       // 端口（可能为 null）
            if (port == null) {
                port = "http".equals(protocol) ? "80" : "443";
            }

            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(host, Integer.parseInt(port)), timeout);
            if (socket.isConnected()) {
                socket.close();
                return true;
            }
            return false;
        } else {
            return false;
        }
    }

}
